package cn.ecut.response;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;


@WebServlet("/header3.do")
public class HeaderServlet3 extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Path path = Path.of("D:\\test.jpg") ;
        // 设置指定的编码
        response.setCharacterEncoding("UTF-8");
        // 在线下载图片
        response.setHeader("content-disposition", "attachment;filename="+path.getFileName().toString()+".jpg");
        // 设置 响应头
//        response.setHeader("content-type" , "image/png; charset=utf-8"); // 在线显示图片

        // 期望页面上显示出来内容
        InputStream inputStream = Files.newInputStream( path );
        ServletOutputStream outputStream = response.getOutputStream();
        int j ;
        while( (j = inputStream.read()) != -1 ){
            outputStream.write( j );
        }

    }
}
